<?php
// 应用公共文件
use app\common\model\Manage;
use app\common\model\User;

/**
 * 功能描述: 格式化API数据
 * @author cou
 */
function show($status,$msg = "",$datas = [],$httpStatus = 200){

    $result = [
        'status' => $status,
        'msg'    => $msg,
        'datas'  => $datas
    ];

    return json($result,$httpStatus);



}

/***
 * 令牌校检
 * @author cou
 * @return array
 */
function validateShopToken()
{
    $_token = input('__token__/s', '');

    if (!$_token || $_token != session('__token__')) {

        if (request()->isAjax()) {
            $return = [
                'data'   => '',
                'msg'    => '已超时或重复提交，请重试或刷新页面',
                'status' => false,
                'token'  => ''
                //'token'  => request()->buildToken('__token__', 'sha1')
            ];

            header('Content-type:text/json');
            echo json_encode($return);
            exit;
        } else {
            die("CSRF is die");
        }
    }

}

/**
 * 生成令牌
 * @author cou
 */
function shopToken()
{
    $data = request()->buildToken('__token__', 'sha1');
    return '<input type="hidden" name="__token__" value="' . $data . '" class="token">';
}


/**
 * 返回当前的毫秒时间戳
 * @author cou
 * @return string
 */
function msectime()
{
    list($tmp1, $tmp2) = explode(' ', microtime());
    return sprintf('%.0f', (floatval($tmp1) + floatval($tmp2)) * 1000);
}


/**
 * 获取最近天数的日期和数据
 * @author cou
 * @param $day
 * @param $data
 * @return array
 */
function get_lately_days($day, $data)
{
    $day  = $day - 1;
    $days = [];
    $d    = [];
    for ($i = $day; $i >= 0; $i--) {
        $d[] = date('d', strtotime('-' . $i . ' day')) . '日';
        $days[date('Y-m-d', strtotime('-' . $i . ' day'))] = 0;
    }
    foreach ($data as $v) {
        $days[$v['day']] = $v['nums'];
    }
    $new = [];
    foreach ($days as $v) {
        $new[] = $v;
    }
    return ['day' => $d, 'data' => $new];
}


/**
 * 获取客户端IP地址
 * @author cou
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean $adv 是否进行高级模式获取（有可能被伪装）
 * @return mixed
 */
function get_client_ip($type = 0, $adv = false)
{
    $type = $type ? 1 : 0;
    static $ip = NULL;
    if ($ip !== NULL) return $ip[$type];
    if ($adv) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos) unset($arr[$pos]);
            $ip = trim($arr[0]);
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}


/**
 * 判断前端浏览器类型
 * @author cou
 * @return bool|string
 */
function get_client_broswer()
{
    $ua = $_SERVER['HTTP_USER_AGENT'];

    //微信内置浏览器
    if (stripos($ua, 'MicroMessenger')) {
        //preg_match('/MicroMessenger\/([\d\.]+)/i', $ua, $match);
        return "weixin";
    }
    //支付宝内置浏览器
    if (stripos($ua, 'AlipayClient')) {
        //preg_match('/AlipayClient\/([\d\.]+)/i', $ua, $match);
        return "alipay";
    }
    return false;
}


/**
 * 数组倒排序，取新的键
 * @author cou
 * @param array $array
 * @return array
 */
function _krsort($array = [])
{
    krsort($array);
    if (is_array($array)) {
        $i          = 0;
        $temp_array = [];
        foreach ($array as $val) {
            $temp_array[$i] = $val;
            $i++;
        }
        return $temp_array;
    } else {
        return $array;
    }
}

/**
 * 返回错误码
 * @author cou
 * @param $code
 * @param bool $mini
 * @return array|mixed
 */
function error_code($code, $mini = false)
{
    $result = [
        'status' => 10000,
        'msg'    => config('error.10000'),
        'datas'   => [],
    ];

    if (config('?error.' . $code)) {
        $result['status'] = $code;
        $result['msg']  = config('error.' . $code);
    }

    if ($mini) {
        return $result['msg'];
    } else {
        return $result;
    }

}

/**
 * 生成编号
 * @author cou
 * @param $type
 * @return string
 */
function get_sn($type)
{
    switch ($type) {
        case 1:         //订单编号
            $str = $type . substr(msectime() . rand(0, 9), 1);
            break;
        case 2:         //支付单编号
            $str = $type . substr(msectime() . rand(0, 9), 1);
            break;
        case 3:         //商品编号
            $str = 'G' . substr(msectime() . rand(0, 5), 1);
            break;
        case 4:         //货品编号
            $str = 'P' . substr(msectime() . rand(0, 5), 1);
            break;
        case 5:         //售后单编号
            $str = $type . substr(msectime() . rand(0, 9), 1);
            break;
        case 6:         //退款单编号
            $str = $type . substr(msectime() . rand(0, 9), 1);
            break;
        case 7:         //退货单编号
            $str = $type . substr(msectime() . rand(0, 9), 1);
            break;
        case 8:         //发货单编号
            $str = $type . substr(msectime() . rand(0, 9), 1);
            break;
        case 9:         //提货单号
            //$str = 'T'.$type.substr(msectime().rand(0,5), 1);
            $chars    = ['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '2', '3', '4', '5', '6', '7', '8', '9'];
            $charsLen = count($chars) - 1;
            shuffle($chars);
            $str = '';
            for ($i = 0; $i < 6; $i++) {
                $str .= $chars[mt_rand(0, $charsLen)];
            }
            break;
        default:
            $str = substr(msectime() . rand(0, 9), 1);
    }
    return $str;
}

/***
 * 获取年月日目录
 * @author cou
 */
function get_date_dir()
{
    $dir = '/' . date('Y') . '/' . date('m') . '/' . date('d');
    return $dir;
}

/**
 * 时间格式化
 * @author cou
 * @param int $time
 * @return false|string
 */
function getTime($time = 0)
{
    return date('Y-m-d H:i:s', $time);
}

/**
 * 返回用户信息
 * @author cou
 * @param $user_id
 * @param string $field
 * @return string
 */
function get_user_info($user_id, $field = 'mobile')
{
    if (!$user_id) {
        return "";
    }
    $user = app\common\model\User::get($user_id);
    if ($user) {
        if ($field == 'nickname') {
            $nickname = $user['nickname'];
            if ($nickname == '') {
                $nickname = format_mobile($user['mobile']);
            }
            return $nickname;
        } else {
            return $user->$field;
        }
    } else {
        return "";
    }
}

/**
 * 返回用户信息
 * @author cou
 * @param $mobile
 * @return bool|mixed
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function get_user_id($mobile)
{
    $userModel = new app\common\model\User();
    $user      = $userModel->where(array('mobile' => $mobile))->find();
    if ($user) {
        return $user->id;
    } else {
        return false;
    }
}


/**
 * 返回管理员信息
 * @author cou
 * @param $manage_id
 * @param string $field
 * @return string
 */
function get_manage_info($manage_id, $field = 'username')
{
    $user = app\common\model\Manage::find($manage_id);
    if ($user) {
        if ($field == 'nickname') {
            $nickname = $user['nickname'];
            if ($nickname == '') {
                $nickname = format_mobile($user['mobile']);
            }
            return $nickname;
        } else {
            return $user->$field;
        }
    } else {
        return "";
    }
}

/***
 * 判断是否json
 * @author cou
 * @param $str
 * @return bool
 */
function isjson($str)
{
    return is_null(json_decode($str)) ? false : true;
}

/**
 * 格式化数据化手机号码
 * @author cou
 * @param $mobile
 * @return string
 */
function format_mobile($mobile)
{
    return substr($mobile, 0, 5) . "****" . substr($mobile, 9, 2);
}


/**
 * 判断是否手机号
 * @author cou
 * @param $mobile
 * @return bool
 */
function isMobile($mobile = '')
{
    if (preg_match("/^1[3456789]{1}\d{9}$/", $mobile)) {
        return true;
    } else {
        return false;
    }
}


/**
 * 秒转换为天，小时，分钟
 * @author cou
 * @param int $second
 * @return string
 */
function secondConversion($second = 0)
{
    $newtime = '';
    $d       = floor($second / (3600 * 24));
    $h       = floor(($second % (3600 * 24)) / 3600);
    $m       = floor((($second % (3600 * 24)) % 3600) / 60);
    if ($d > '0') {
        if ($h == '0' && $m == '0') {
            $newtime = $d . '天';
        } else {
            $newtime = $d . '天' . $h . '小时' . $m . '分';
        }
    } else {
        if ($h != '0') {
            if ($m == '0') {
                $newtime = $h . '小时';
            } else {
                $newtime = $h . '小时' . $m . '分';
            }
        } else {
            $newtime = $m . '分';
        }
    }
    return $newtime;
}


/**
 * 返回图片地址
 * @author cou
 */
function _sImage($image_id = '', $type = 's')
{
    if (!$image_id) {
        $image_id = getSetting('shop_default_image');//系统默认图片
        if (!$image_id) {
            return config('shop.default_image');//默认图片
        }
    }

    if (stripos($image_id, 'http') !== false || stripos($image_id, 'https') !== false) {
        return $image_id;
    }

    $image_obj = new \app\common\model\Images();
    $image     = $image_obj->where([
        'id' => $image_id
    ])->field('url')->cache(true)->find();
    if ($image) {
        if (stripos($image['url'], 'http') !== false || stripos($image['url'], 'https') !== false) {
            return str_replace("\\", "/", $image['url']);
        } else {
            return request()->domain() . str_replace("\\", "/", $image['url']);
        }
    } else {
        return config('shop.default_image');//默认图片
    }
}


/**
 * 相对地址转换为绝对地址
 * @author cou
 * @param string $url
 * @return string
 */
function getRealUrl($url = '')
{
    if (stripos($url, 'http') !== false || stripos($url, 'https') !== false) {
        return $url;
    } else {
        $storage_params = getSetting('image_storage_params');
        if (isset($storage_params['domain']) && $storage_params['domain']) {
            return $storage_params['domain'] . $url;
        }
        if (config('shop.image_storage.domain')) {
            return config('shop.image_storage.domain') . $url;
        }
        return request()->domain() . $url;
    }
}

/**
 * 获取hash值
 * @author cou
 * @return string
 */
function get_hash()
{
    $chars   = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()+-';
    $random  = $chars[mt_rand(0, 73)] . $chars[mt_rand(0, 73)] . $chars[mt_rand(0, 73)] . $chars[mt_rand(0, 73)] . $chars[mt_rand(0, 73)];
    $content = uniqid() . $random;
    return sha1($content);
}


/**
 * 获取系统设置
 * @author cou
 * @param string $key
 * @return mixed|string
 */
function getSetting($key = '')
{
    $systemSettingModel = new \app\common\model\Setting();
    return $systemSettingModel->getValues($key);
}


/**
 * 获取多个系统设置
 * @author cou
 * @param string $key //多个英文逗号分隔
 * @return array
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function getMultipleSetting($key = '')
{
    $systemSettingModel = new \app\common\model\Setting();
    return $systemSettingModel->getMultipleValue($key);
}


